package com.pj.oauth2;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Consts;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Handle;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Sa-OAuth2 Server端 控制器
 * @author kong
 * 
 */
@RestController
public class SaOAuth2ServerController {


	private static Map<String,String> usersMap = new HashMap<>(16);

	static {
		usersMap.put("test1","123456");
		usersMap.put("test2","123456");
		usersMap.put("test3","123456");
		usersMap.put("test4","123456");
		usersMap.put("test5","123456");
		usersMap.put("test6","123456");
		usersMap.put("test7","123456");

	}
	// Sa-OAuth2 定制化配置 
	@Autowired
	public void setSaOAuth2Config(SaOAuth2Config cfg) {
		cfg.
			// 未登录的视图 
			setNotLoginView(()->{
				return SaResult.error().setCode(401).setMsg("未登录");
			}).
			// 登录处理函数 
			setDoLoginHandle((name, pwd) -> {
				String clientName = usersMap.get(name);
				if(clientName != null && clientName.equals(pwd)){
					StpUtil.login(name);
					return SaResult.ok();
				}
				return SaResult.error("账号名或密码错误");
			}).
			// 授权确认视图 
			setConfirmView((clientId, scope)->{
				Map<String, Object> map = new HashMap<>(16);
				map.put(SaOAuth2Consts.Param.client_id, clientId);
				map.put(SaOAuth2Consts.Param.scope, scope);
				String loginId = StpUtil.getLoginIdAsString();
				String redisKey = "byt-a:oauth:confirm:expireStr:"+clientId+":"+scope+":"+loginId;
				// 存入redis redisKey 过期时间
				map.put("logo","https://img2.baidu.com/it/u=4113082695,1479965454&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500");
				map.put("fullName","长城网");
				map.put("shortName","81t测试demo");
				return  SaResult.get(200,"跳转授权页面",map);
			})
			;
	}


	// ---------- 开放相关资源接口： Client端根据 Access-Token ，置换相关资源 ------------ 
	
	// 获取Userinfo信息：昵称、头像、性别等等
	@RequestMapping("/userInfo")
	public SaResult userinfo() {
		// 获取 Access-Token 对应的账号id 
		String accessToken = SaHolder.getRequest().getParamNotNull("token");
		Object loginId = SaOAuth2Util.getLoginIdByAccessToken(accessToken);
		System.out.println("-------- 此Access-Token对应的账号id: " + loginId);
		
		// 校验 Access-Token 是否具有权限: userinfo
		SaOAuth2Util.checkScope(accessToken, "userinfo");
		
		// 模拟账号信息 （真实环境需要查询数据库获取信息）
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("nickname", loginId);
		map.put("userImg", "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F49568d71j00sd90qe0015d000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg");
		return SaResult.data(map);
	}
	
}
